﻿using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using JetBrains.Annotations;
using Kaleida.ServiceMonitor.Model;
using Kaleida.ServiceMonitor.Model.Runtime;

namespace Kaleida.ServiceMonitor.UI
{
    public partial class AboutControl : UserControl
    {
        private string versionCheckSummary;

        public AboutControl()
        {
            InitializeComponent();
            UpdateVersionLabel();

            lblProcessInfo.Text = string.Format("Current process id: " + Process.GetCurrentProcess().Id);
        }

        public void PopulateOperationsHelp([NotNull] RuntimeEnvironment runtimeEnvironment)
        {
            if (runtimeEnvironment == null) throw new ArgumentNullException("runtimeEnvironment");
            wbOperationsHelp.Navigate("about:blank");
            if (wbOperationsHelp.Document != null)
            {
                string htmlHelp = ReflectionOperationHtmlHelpBuilder.GetOperationsHtmlHelp(runtimeEnvironment);
                wbOperationsHelp.Document.Write(htmlHelp);
            }
        }

        public void SetVersionCheckStatus(string summary, string fullDetails = null)
        {
            if (fullDetails != null)
            {

                var tooltip = new ToolTip();
                tooltip.SetToolTip(labelVersion, fullDetails);
            }

            versionCheckSummary = summary;

            UpdateVersionLabel();
        }

        private void UpdateVersionLabel()
        {
            var summary = new StringBuilder();
            summary.AppendFormat("Version {0}", ServiceMonApplication.VersionNumber);

            if (versionCheckSummary != null)
            {
                summary.AppendFormat(" ({0})", versionCheckSummary);
            }

            labelVersion.Text = summary.ToString();
        }

        private static void BrowseTo(string url)
        {
            var sInfo = new ProcessStartInfo(url);
            Process.Start(sInfo);
        }

        private void linkHomepage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BrowseTo("https://www.rightcalc.com/blog/servicemon/");
        }

        private void linkKaleida_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BrowseTo("http://www.kaleida.co.uk/");
        }

        private void linkReportIssue_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BrowseTo("http://servicemon.codeplex.com/WorkItem/Create");
        }
    }
}
